package com.blog.configuration;

import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 本地缓存配置
 *
 * @author Joy
 * @date 2020-12-26
 */
@Configuration
public class LocalCacheConfig {

    private static final Logger LOG = LoggerFactory.getLogger(LocalCacheConfig.class);

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Bean
    public CacheLoader<Object, Object> localCacheLoader(){
        return key -> redisTemplate.opsForValue().get(key.toString());
    }

    @Bean("caffeineLocalCache")
    public Cache<Object, Object> localCache(CacheLoader<Object,Object> cacheLoader,
        @Qualifier("threadPoolTaskExecutor") Executor executor){
        return Caffeine.newBuilder().expireAfterWrite(3, TimeUnit.MINUTES).recordStats().maximumSize(1000L).executor(executor).build(cacheLoader);
    }
}


